package dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import databean.ItemBean;

import utility.Util_Finding;

public class FindItemsByKeywordsDAO {
	
	private static String timestamp;
	private static String message;
	
	public static String getTimestamp() {
		return timestamp;
	}
	
	public static String getMessage() {
		return message;
	}
	
	public static List<ItemBean> findItemsByKeywords(String keyword) {
		
		HashMap<String,String> data=new HashMap<String,String>();
		data.put("keywords", keyword);
		
		Document response = Util_Finding.sendRequest("findItemsByKeywords.txt", data);
	    
		
		try {
			
			message = response.getElementsByTagName("message").item(0).getChildNodes().item(0).getNodeValue();
			return null;
			
		} catch (NullPointerException e) {
			
			timestamp = response.getElementsByTagName("timestamp").item(0).getChildNodes().item(0).getNodeValue();

			NodeList ids = response.getElementsByTagName("itemId");
			int len = ids.getLength();
			
			NodeList titles = response.getElementsByTagName("title");
			NodeList categoryNames = response.getElementsByTagName("categoryName");
			NodeList viewItemURLs = response.getElementsByTagName("viewItemURL");
			NodeList locations = response.getElementsByTagName("location");
			NodeList startTimes = response.getElementsByTagName("startTime");
			NodeList endTimes = response.getElementsByTagName("endTime");
			//NodeList conditionDisplayNames = response.getElementsByTagName("conditionDisplayName");
			NodeList currentPrices = response.getElementsByTagName("currentPrice");
			 
			List<ItemBean> beans = new ArrayList<ItemBean>();
			
			for(int i=0;i<len;i++){
				
				ItemBean bean = new ItemBean();
				bean.setItemID(geti(ids,i));
				bean.setTitle(geti(titles,i));
				bean.setCategoryName(geti(categoryNames,i));
				bean.setViewItemURL(geti(viewItemURLs,i));
				bean.setLocation(geti(locations,i));
				bean.setStartTime(geti(startTimes,i));
				bean.setEndTime(geti(endTimes,i));
				//bean.setConditionDisplayName(geti(conditionDisplayNames,i));
				bean.setCurrentPrice(geti(currentPrices,i));
				beans.add(bean);
				
			}
			return beans;
			
		}		
				
	}
	
	private static String geti(NodeList list,int i){
    	return list.item(i).getChildNodes()
		.item(0).getNodeValue();
    }
	
}
 